home *** CD-ROM | disk | FTP | other *** search
- Path: user2.mnsinc.com!huang
- From: huang@mnsinc.com (Szu-Wen Huang)
- Newsgroups: comp.lang.c,comp.lang.c++
- Subject: Re: [Q] Multi-dimensional array problem!!!!!
- Followup-To: comp.lang.c,comp.lang.c++
- Date: 18 Apr 1996 23:15:48 GMT
- Organization: Monumental Network Systems
- Message-ID: <4l6if4$ebe@news1.mnsinc.com>
- References: <4l651f$p8v@oldfart.ecl.wustl.edu>
- NNTP-Posting-Host: user.mnsinc.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Kyeong Soo Kim (kks@rgit.wustl.edu) wrote:
- [snip]
- : But, in my case, the dimension as well as the size of the
- : array is also an input parameter for the program. That is,
- : while I must treat 3x4 array in one situation, I must treat
- : 3x4x5 array in the other situation. One of the most simple
- : example is as follows:
- [snip]
-
- Not that big a problem. Here's how I'd solve it: Allocate a
- one-dimensional memory chunk as usual that can hold the
- multi-dimensional array. In English this would be:
-
- x = malloc(size(dim1)*size(dim2)...sizeof(dimn));
-
- Since the dimension is variable, the size might be computed in
- a loop like so:
-
- for (i=0; i<NUMBER_OF_DIMENSIONS; i++)
- totalsize *= SIZE_OF_DIMENSION[i];
- x = malloc(totalsize);
-
- Now, having a big enough space to work on, we must now be able
- to address any element in the multi-dimensional array. In general,
- element[subscript1][subscript2]...[subscriptn] can be stored in
- x[subscript1 * sum(size(dim2)..size(dimn)) +
- subscript2 * sum(size(dim3)..size(dimn)) +
- ...
- subscript(n-1) * size(dimn) +
- subscriptn]
-
- *or*
-
- x[subscript1 +
- subscript2 * size(dim1) +
- ...
- subscriptn * sum(size(dim1)..size(dim(n-1)))]
-
- The former is called row-major and the latter column-major. There
- are various performance reasons why you want to use one over the
- other, but I'll leave that out unless you are really interested.
-
- Coding the former in C might look like:
-
- for (i=0; i<NUMBER_OF_DIMENSIONS; i++) {
- for (j=i+1; j<NUMBER_OF_DIMENSIONS; j++)
- rowsize += SIZE_OF_DIMENSION[j];
- index += SUBSCRIPT[i] * rowsize;
- }
- x[index] is the element we look for
-
- Okay, I hope this solves your problem. Note that the C code I
- posted won't run as is because they are only meant to show what
- the actual code might look like and are missing initializations
- and range checks. You should be able to produce working code
- from here on. Hope this helps.
-